package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TrackUpdateUserPaidRecord implements UpdateUserPaidRecordStrategy {

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient ;

    @Autowired
    private UserPaidTrackService userPaidTrackService ;

    @Override
    public void updateUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {

        // 保证接口的幂等性
        LambdaQueryWrapper<UserPaidTrack> lambdaQueryWrapper = new LambdaQueryWrapper<>() ;
        lambdaQueryWrapper.eq(UserPaidTrack::getOrderNo , userPaidRecordVo.getOrderNo())  ;
        long count = userPaidTrackService.count(lambdaQueryWrapper);
        if(count > 0) {
            log.info("orderNo： {} 的声音的购买信息已经保存了，无需再次进行保存...." , userPaidRecordVo.getOrderNo());
            return;
        }

        // 声音购买保存购买信息
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();

        // 根据声音的id查询声音信息
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(itemIdList.get(0));
        TrackInfo trackInfo = trackInfoResult.getData();

        List<UserPaidTrack> paidTrackList = itemIdList.stream().map(trackId -> {
            UserPaidTrack userPaidTrack = new UserPaidTrack();     // 通过该对象封装要保存的购买的声音信息
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(trackId);
            return userPaidTrack;
        }).collect(Collectors.toList());
        userPaidTrackService.saveBatch(paidTrackList) ;

    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_TRACK;    // 1002
    }

}
